//
//  MaintenceServiceView.swift
//  koolcar
//
//  Created by xiantian on 2023/10/25.
//

import UIKit
import FSCalendar


class MaintenceServiceView: UIView {
    var curDateStr = XTManageCenter.getDateStringNow()
    
    var dateFormatter: DateFormatter = {
        let tempForm = DateFormatter()
        tempForm.dateFormat = "yyyy-MM-dd"
        return tempForm
    }()
    var leftBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.frame = CGRect.init(x: 0, y: 0, width: 60, height: 40)
        tempBtn.backgroundColor = .white
        tempBtn.setup_image(image: UIImage.init(named: "calendar_left"))
        return tempBtn
    }()
    var rightBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.frame = CGRect.init(x: kScreenWidth - 60, y: 0, width: 60, height: 40)
        tempBtn.backgroundColor = .white
        tempBtn.setup_image(image: UIImage.init(named: "calendar_right"))
        return tempBtn
    }()
    var calendarView: FSCalendar!
    var tableView: UITableView!
    var showAllBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "maintence_arrow_down"))
        return tempBtn
    }()
    var todayStr = XTManageCenter.getDateDistanceNow(days: 0)
    ///日历展示列表
    var calenderList: [CalenderAvailabilityDataModel] = []
    ///日历选中当天对应的时间段
    var timeList: [TimeAvailabilityDataModel] = []
    ///选中当前日期
    var selectDate: Date? = nil
    ///商品服务列表
    var serverProductList: [ServerProductContentModel] = []
    
    var storeList: [StoreUsedcarListModel] = []
    var selectStoreIndex: NSInteger = 0 //选中门店下标
    var bookDay: NSInteger = 30 //最大可预约天数
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = true
        self.backgroundColor = Theme.viewBkgGrayColor
        //FSCalendarConstants调整大小
        self.calendarView = FSCalendar(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 358))
        self.calendarView.register(MaintenceDIYDateCell.self, forCellReuseIdentifier: "MaintenceDIYDateCell")
        self.calendarView.dataSource = self
        self.calendarView.delegate = self
        self.calendarView.scope = .week
        self.calendarView.backgroundColor = .white
        self.calendarView.appearance.borderRadius = 0
        self.calendarView.appearance.todayColor = nil //Theme.whiteColor
        self.calendarView.appearance.selectionColor = UIColor.init(hex: 0xFFCC32, alpha: 0.3)
        self.calendarView.appearance.borderSelectionColor = UIColor.init(hex: 0xFFCC32, alpha: 1)
        self.calendarView.appearance.titleSelectionColor = Theme.titleLabColor
        self.calendarView.appearance.titleTodayColor = Theme.titleLabColor
        self.calendarView.appearance.headerTitleColor = Theme.titleLabColor
        self.calendarView.appearance.weekdayTextColor = Theme.placeholderColor
        self.calendarView.appearance.weekdayFont = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        self.calendarView.appearance.titleFont = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        self.calendarView.appearance.headerDateFormat = "yyyy-MM"
        self.calendarView.calendarHeaderView.collectionView.isUserInteractionEnabled = true
//        self.calendarView.appearance.calendar.placeholderType = .fillSixRows
        self.calendarView.addSubview(self.leftBtn) //上一个月
        self.calendarView.addSubview(self.rightBtn) //下一个月
        leftBtn.addTarget(self, action: #selector(leftBtnAction), for: .touchUpInside)
        rightBtn.addTarget(self, action: #selector(rightBtnAction), for: .touchUpInside)
        // [NSLocale localeWithLocaleIdentifier:@"zh-CN"]
        var tempLocal = "zh-CN"
        let curLan = XTManageCenter.getAppleLanguages()
        switch curLan {
            case AppLanguage.english.rawValue:
                tempLocal = "en"
            case AppLanguage.chinese_hk.rawValue:
                tempLocal = "zh-HK"
            default:
                ()
        }
        self.calendarView.locale = Locale.init(identifier: tempLocal)
        self.addSubview(self.calendarView)
        
        self.showAllBtn.addTarget(self, action: #selector(self.showAllBtnAction), for: .touchUpInside)
        self.addSubview(self.showAllBtn)
        
        //添加手势
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleScopeGesture11(pan:)))
        panGesture.delegate = self
        panGesture.minimumNumberOfTouches = 1
        panGesture.maximumNumberOfTouches = 2
        self.addGestureRecognizer(panGesture)
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 300, width: kScreenWidth, height: kScreenHeight - NavBarHight - TabbarHeight), style: .grouped)
        
        tableView.register(MaintenceDateNewCell.self, forCellReuseIdentifier: "MaintenceDateNewCell")
        tableView.register(MaintenceTimeCell.self, forCellReuseIdentifier: "MaintenceTimeCell")
        tableView.register(MaintenceServiceTypeCell.self, forCellReuseIdentifier: "MaintenceServiceTypeCell")
        tableView.register(MaintenceAddressTableCell.self, forCellReuseIdentifier: "MaintenceAddressTableCell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = Theme.viewBkgGrayColor
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.delaysContentTouches = false
        tableView.estimatedRowHeight = 2
        tableView.bounces = true
        self.addSubview(tableView)
        
        let tableHeaderView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 0.01))
        tableHeaderView.backgroundColor = Theme.viewBkgGrayColor
        self.tableView.tableHeaderView = tableHeaderView
        
        self.addSnpLayout()
        let footerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 140))
        footerView.backgroundColor = Theme.viewBkgGrayColor
        
        let confirmBtn = UIButton()
        confirmBtn.setBackgroundImage(UIImage.init(color: Theme.mainColor), for: .normal)
        confirmBtn.setBackgroundImage(UIImage.init(color: Theme.mainColorHighLightColor), for: .highlighted)
        confirmBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        confirmBtn.layer.cornerRadius = 8
        confirmBtn.layer.masksToBounds = true
        confirmBtn.setup_titleLabel(text: MMLocalizedString("mainten_book_now", comment: "立即预约"))
        confirmBtn.setup_titleColor(color: .white)
        confirmBtn.addTarget(self, action: #selector(confirmBtnAction), for: .touchUpInside)
        footerView.addSubview(confirmBtn)
        confirmBtn.snp.makeConstraints { make in
            make.left.equalTo(14)
            make.right.equalTo(-14)
            make.centerY.equalTo(90)
            make.height.equalTo(46)
        }
        footerView.layoutIfNeeded()
        tableView.tableFooterView = footerView
    }
    
    @objc func showAllBtnAction(){
        if self.calendarView.scope == .month {
            self.calendarView.scope = .week
        }else{
            self.calendarView.scope = .month
        }
        self.calendarView.reloadData()
    }
    
    public func fetchGetRequest(){
        self.fetchGetAddress() //获取门店地址
        self.fetchGetServerProductList() //服务列表
        self.fetchAvailabilityList() //日历
    }
    
    ///手势处理 tableview与日历中的手势
    @objc func handleScopeGesture11(pan: UIPanGestureRecognizer) {
        let transY = pan.translation(in: self).y
        if self.calendarView.scope == .month {
            if transY > 0 {return}
        }
        if self.calendarView.scope == .week && transY <= 0 {
            return
        }
        self.calendarView.transitionCoordinator.handleScopeGesture(pan)
    }
    
    
    private func addSnpLayout(){
        self.calendarView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(0)
            make.height.equalTo(358)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(self.calendarView.snp.bottom).offset(20)
            make.bottom.equalTo(0)
        }
        
        showAllBtn.snp.makeConstraints { make in
            make.width.equalTo(24)
            make.height.equalTo(24)
            make.centerX.equalTo(kScreenWidth/2)
            make.centerY.equalTo(calendarView.snp.bottom)
        }
    }
    
    ///获取门店地址
    private func fetchGetAddress(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.commonIndexDetail, objectType: IndexBaseResModel.self) { data in
            let resultObj = data as! IndexBaseResModel
            if resultObj.code == "1" {
                self.storeList = resultObj.data?.storeUsedcarList ?? []
                self.tableView.reloadData()
            }else{
                self.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///获取服务列表
    private func fetchGetServerProductList(){
        let param: [String: String] = ["pageSize":"9999", "pageNumber":"1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.serverProductPage(param: param), objectType: ServerProductResModel.self) { data in
            let resultObj = data as! ServerProductResModel
            if resultObj.code == "1" {
                let tempArr = resultObj.data?.content ?? []
//                tempArr.forEach { item in
//                    item.selectProductBlock = {[weak self] in
//                        self?.didSelectServerProductItem(selectProduct: item)
//                    }
//                }
                
                //设置选中项
                let tempIds = self.getSelectProductIds()
                tempArr.forEach { item in
                    if tempIds.contains(item.id ?? 0) {
                        item.selectFlag = true
                    }else{
                        item.selectFlag = false
                    }
                }
                self.serverProductList = tempArr
                self.tableView.reloadData()
            }else{
                self.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///获取选中的服务[id]
    private func getSelectProductIds() -> [Int]{
        guard self.serverProductList.count > 0 else {
            return []
        }
        return self.serverProductList.filter{$0.selectFlag}.map{$0.id ?? 0}
    }
    
    ///选中商品服务
//    private func didSelectServerProductItem(selectProduct: ServerProductContentModel){
//        self.serverProductList.forEach { product in
//            if product.id != selectProduct.id {
//                product.selectFlag = false
//            }
//        }
        //self.tableView.reloadSection(1, with: .none)
//    }
    
    ///当月日历预约数据展示
   private func fetchAvailabilityList(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingAvailabilityList, objectType: CalenderAvailabilityResModel.self) { data in
            let resultObj = data as! CalenderAvailabilityResModel
            if resultObj.code == "1" {
                self.bookDay = resultObj.extData?.bookDay ?? 0
                let tempArr = resultObj.data ?? []
                self.calenderList = tempArr
                self.calendarView.reloadData()
                self.calendarView.layoutIfNeeded()
                self.defaultSelectCalendar()
            }else{
                self.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///默认选中日历
    private func defaultSelectCalendar(){
        guard self.selectDate != nil else {
            return
        }
        self.calendarView.select(self.selectDate, scrollToDate: false)
        self.calendarView.setCurrentPage(self.selectDate!, animated: true)
        self.fetchAvailabilityDate()
    }
    
    ///单个日历可预约时间段
    private func fetchAvailabilityDate(){
        self.showLoadingHUDText()
        let param: [String: String] = ["date": self.dateFormatter.string(from: self.selectDate ?? Date())]
         XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingAvailabilitySelectDay(param: param), objectType: TimeAvailabilityResModel.self) { data in
             self.handleLoading()
             let resultObj = data as! TimeAvailabilityResModel
             if resultObj.code == "1" {
                 let tempArr = resultObj.data ?? []
                 //当前的time时间
                 let tempCurTime = XTManageCenter.getDateTimeStringNow(format: "yyyy-MM-dd HH:mm")
                 tempArr.forEach { timeObj in
                     timeObj.selectTimeBlock = {[weak self] in
                         timeObj.selectFlag = !timeObj.selectFlag
                         self?.didSelectTimeItem(selectObj: timeObj)
                     }
                     //设置当天的time以前的不可选 yyyy-MM-dd HH:mm
                     let tempFullDateTime = String(format: "%@ %@",
                                                   (timeObj.joinDate ?? "").substring(to: 10),
                                                   (timeObj.endTime ?? "").substring(to: 5))
                     if tempFullDateTime < tempCurTime {
                         timeObj.status = 0
                     }
                 }
                 //默认第一个status=1的可选
                 let firObj = tempArr.first(where: {$0.status ?? 0 == 1})
                 firObj?.selectFlag = true
                 self.timeList = tempArr
                 self.tableView.reloadData()
             }else{
                 self.makeToast(message: resultObj.msg ?? "")
             }
         } error: { err in
             self.handleLoading()
             self.makeToast(message: err?.domain ?? "")
         }
     }
    
    ///选中时间段事件
    private func didSelectTimeItem(selectObj: TimeAvailabilityDataModel){
        self.timeList.forEach { item in
            if item.slotId != selectObj.slotId {
                item.selectFlag = false
            }
        }
        self.tableView.reloadSection(0, with: .none)
    }
    
    ///上一个月
    @objc func leftBtnAction(){
        self.calendarView.setCurrentPage(calendarView.currentPage.getLastDate(), animated: true)
    }
    
    ///下一个月
    @objc func rightBtnAction(){
        self.calendarView.setCurrentPage(calendarView.currentPage.getNextDate(), animated: true)
        
    }
    
    ///立即预约
    @objc private func confirmBtnAction(){
        if UserModule.shared.isLogined == false {
            XTManageCenter.shared.jumpToLoginView()
            return
        }
        
        let findIds = self.serverProductList.filter{$0.selectFlag}
        if findIds.count == 0 {
            self.makeToast(message: MMLocalizedString("my_reserver_product", comment: "请选择商品"))
            return
        }
        
        guard let timeObj = self.timeList.first(where: {$0.selectFlag}) else {
            self.makeToast(message: MMLocalizedString("mainten_select_time", comment: "请选择时段"))
            return
        }
        
        if self.storeList.count < self.selectStoreIndex {
            self.makeToast(message: MMLocalizedString("please_select_address", comment: "请选择门店地址"))
            return
        }
       
        let time = String(format: "%@\n%@~%@",
                          (timeObj.joinDate ?? "").substring(to: 10),
                          (timeObj.startTime ?? "").substring(to: 5),
                          (timeObj.endTime ?? "").substring(to: 5))
        let msgTip = String(format: MMLocalizedString("mainten_confirm_book", comment: "确定预约 %@ 服务"), time)
        let alertView = ServiceAlertView.init(title:
                                                MMLocalizedString("add_tip", comment: "提示"),
                                              message: msgTip,
                                              cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                              otherButtonTitles: [MMLocalizedString("confirm", comment: "确定")])
                alertView.alertType = .inputAlert
                alertView.placeHolder = MMLocalizedString("mainten_input_brand", comment: "请输入车牌号")
                alertView.clickButtonBlock = {[weak self] (tag, inputVal) in
                    if tag == 1 {
                        self?.createOrder(carBrand: inputVal)
                    }
                }
                alertView.show()
    }
    
    private func createOrder(carBrand: String){
        if carBrand == "" {
            self.makeToast(message: MMLocalizedString("mainten_input_brand", comment: "请输入车牌号"))
            return
        }
        
        let findProductArr = self.serverProductList.filter{$0.selectFlag}
        if findProductArr.count == 0 {
            self.makeToast(message: MMLocalizedString("my_reserver_product", comment: "请选择商品"))
            return
        }
        
        guard let timeObj = self.timeList.first(where: {$0.selectFlag}) else {
            self.makeToast(message: MMLocalizedString("mainten_select_time", comment: "请选择时段"))
            return
        }
    
        let idStr = findProductArr.map{"\($0.id ?? 0)"}.joined(separator: ",")

        let store = self.storeList[self.selectStoreIndex]

        var param = NSMutableDictionary() as! [String: String]
        param["quantity"] = "1"  //预约数量填1就行
        param["serverId"] = idStr //"\(product.id ?? 0)"  //预约的服务id
        param["endTime"] = String(format: "%@", timeObj.endTime ?? "")  //预约结束时间
        param["startTime"] = String(format: "%@", timeObj.startTime ?? "")   //预约开始时间
        param["slotId"] = "\(timeObj.slotId ?? 0) "    //预约时间段 粤B 12345
        param["carNumber"] = carBrand //预约车牌号
        param["storeId"] = "\(store.id ?? 0)"   //预约的门店id
        param["joinDate"] = timeObj.joinDate ?? ""  //预约时间
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingOrderManagerCreateServerOrder(param: param), objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                let vc = MSServiceSuccessViewController()
                self.currentViewController()?.navigationController?.pushViewController(vc, animated: true)

            } else if resultObj.code == "2" {
                //预约过了
                ServiceAlertView.showAlertView(title: MMLocalizedString("add_tip", comment: "提示"),
                                               message: MMLocalizedString("mainten_has_book", comment: "您已预约过，每日只能预约一次服务"),
                                               cancelButtonTitle:
                                                MMLocalizedString("mainten_check_book", comment:"查看预约"),
                                               otherButtonTitlesArr: [MMLocalizedString("mainten_i_know", comment: "知道了")])
                { [weak self] (tagIndex, _) in
                    if tagIndex == 0 {
                         let vc = MyReservationViewController()
                        self?.currentViewController()?.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            } else{
                self.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.makeToast(message: err?.domain ?? "")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension MaintenceServiceView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
            case 0:
                //时间段
                return self.timeList.count > 0 ? 1 : 0
            case 2:
                //门店列表
                return self.storeList.count
            default:
                return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "MaintenceTimeCell", for: indexPath) as! MaintenceTimeCell
                //时间段
                if self.timeList.count > indexPath.row {
                    cell.setMaintenceTimeCell(data: self.timeList)
                }
                cell.clipsToBounds  = true
                cell.selectionStyle = .none
                return cell
            case 1:
                let cell = tableView.dequeueReusableCell(withIdentifier: "MaintenceServiceTypeCell", for: indexPath) as! MaintenceServiceTypeCell
                cell.setMaintenceServiceTypeCell(data: self.serverProductList)
                cell.clipsToBounds  = true
                cell.selectionStyle = .none
                return cell
            case 2:
                let cell = tableView.dequeueReusableCell(withIdentifier: "MaintenceAddressTableCell", for: indexPath) as! MaintenceAddressTableCell
                if self.storeList.count > indexPath.row {
                    let storeItem = self.storeList[indexPath.row]
                    cell.setMaintenceAddressTableCell(data: storeItem)
                }
                if self.selectStoreIndex == indexPath.row {
                    cell.selectImgBtn.isHidden = false
                }else{
                    cell.selectImgBtn.isHidden = true
                }
                
                cell.clipsToBounds  = true
                cell.selectionStyle = .none
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "space", for: indexPath)
                return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 2 else {
            return
        }
        if self.selectStoreIndex == indexPath.row {
            //取消选中
            self.selectStoreIndex = 9999
            self.tableView.reloadSection(2, with: .none)
            return
        }
        self.selectStoreIndex = indexPath.row
        self.tableView.reloadSection(2, with: .none)
    }
}


extension MaintenceServiceView: FSCalendarDataSource, FSCalendarDelegate {
    
    func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool) {
        let offsetY = bounds.height * CGFloat(60.0/358.0) - 60
        self.calendarView.snp.updateConstraints { make in
            make.top.equalTo(offsetY)
            make.height.equalTo(bounds.height)
        }
        if self.calendarView.scope == .month {
            self.tableView.isScrollEnabled = false
            self.showAllBtn.setup_image(image: UIImage.init(named: "maintence_arrow_up"))
        }else{
            self.tableView.isScrollEnabled = true
            self.showAllBtn.setup_image(image: UIImage.init(named: "maintence_arrow_down"))
        }
        self.layoutIfNeeded()
    }
    
    
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        if self.selectDate == date {
            //选中后返选操作(取消)
            self.selectDate = nil
            self.timeList = []
            self.calendarView.deselect(date)
            self.tableView.reloadData()
            return
        }
        self.selectDate = date
        if monthPosition == .next || monthPosition == .previous {
            calendar.setCurrentPage(date, animated: true)
        }
        self.fetchAvailabilityDate()
    }
    
    func maximumDate(for calendar: FSCalendar) -> Date {
        let maxDate = XTManageCenter.getDateDistanceNow(days: self.bookDay)
        return self.dateFormatter.date(from: maxDate) ?? Date()
    }
    
    func minimumDate(for calendar: FSCalendar) -> Date {
        let minDate = XTManageCenter.getDateDistanceNow(days: 0)
        return self.dateFormatter.date(from: minDate) ?? Date()
        
    }
    
    ///设置左右剪头样式
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        let curDateStr = "\(self.dateFormatter.string(from: calendar.currentPage))"
        let curYearMonthStr = curDateStr.substring(to: 7)
        let minYearMonth = self.dateFormatter.string(from: self.calendarView.minimumDate)
        let maxYearMonth = self.dateFormatter.string(from: self.calendarView.maximumDate)
        
        self.rightBtn.isUserInteractionEnabled = true
        self.rightBtn.alpha = 1
        self.leftBtn.isUserInteractionEnabled = true
        self.leftBtn.alpha = 1
        
        if curYearMonthStr == maxYearMonth.substring(to: 7) {
            self.rightBtn.alpha = 0.5
            self.rightBtn.isUserInteractionEnabled = false
        }
        
        if curYearMonthStr == minYearMonth.substring(to: 7) {
            self.leftBtn.alpha = 0.5
            self.leftBtn.isUserInteractionEnabled = false
        }
        
    }
    
    func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell = calendar.dequeueReusableCell(withIdentifier: "MaintenceDIYDateCell", for: date, at: position) as! MaintenceDIYDateCell
        let dateStr = self.dateFormatter.string(from: date)
        let maxDateStr = self.dateFormatter.string(from: self.calendarView.maximumDate)
        if  dateStr < self.curDateStr {
            //当前日期以前的不选
            cell.setDiyCellType(type: .server_disable, isToday: false)
        } else if dateStr > maxDateStr {
            //最大日期以后
            cell.setDiyCellType(type: .server_disable, isToday: false)
        } else {
            let type = self.getCellType(date: date)
            cell.setDiyCellType(type: type, isToday: dateStr == self.curDateStr)
        }
        return cell
    }
    
    ///status 0:关闭，2已满 1可预约
    private func getCellType(date: Date) -> MaintenceDIYDateCellType {
        let dateStr = self.dateFormatter.string(from: date)
        let firObj = self.calenderList.first(where: {$0.joinDate ?? "" == dateStr})
        if firObj == nil {
            //其它日期， 默认可选
            if self.selectDate == nil {
                self.selectDate = date
            }
            return .server_enable
            //return .server_disable
        }
        
        switch firObj?.status ?? 0 {
            case 0:
                return .server_disable
            case 2:
                return .server_full
            default:
            
                if self.selectDate == nil {
                    self.selectDate = date
                }
                return .server_enable
        }
    }
}


extension MaintenceServiceView: UIGestureRecognizerDelegate {
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
}
